package pers.vic.xqd.protocol.http;

import org.apache.commons.io.IOUtils;
import pers.vic.xqd.framerwork.Invocation;
import pers.vic.xqd.provider.LocalRegister;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 描述: 处理请求 返回结果
 * @author Vic.xu
 * @date 2022-02-07 17:48
 */
public class HttpServerHandler {

    public void handle(ServletRequest req, ServletResponse res){

        try {
            ServletInputStream inputStream = req.getInputStream();
            ObjectInputStream ois = new java.io.ObjectInputStream(inputStream);
            Invocation invocation = (Invocation) ois.readObject();
            Class implClass = LocalRegister.get(invocation.getInterfaceName());
            Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            String result = (String) method.invoke(implClass.newInstance(), invocation.getParams());

            IOUtils.write(result, res.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
